<template>
  <div>
    <el-tag
      v-for="tag in tags"
      :key="String(tag)"
      closable
      :disable-transitions="false"
      @close="handleTagClose(tag)"
    >
      {{ tag }}
    </el-tag>
    <el-input
      v-if="keywordsVisible"
      ref="saveKeywordsInput"
      v-model="keywordsInputValue"
      class="input-new-tag"
      size="small"
      @keyup.enter.native="handleKeywordsInputConfirm"
      @blur="handleKeywordsInputConfirm"
    />
    <el-button
      v-else
      class="button-new-tag"
      size="small"
      @click="showKeywordsInput"
    >
      + {{ $t('jspTags.add') }}
    </el-button>
  </div>
</template>

<script>
export default {
  name: 'JspTags',
  props: {
    limit: {
      type: Number,
      default: 0 // 0代表不限制
    },
    data: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      tags: this.data,
      keywordsVisible: false,
      keywordsInputValue: ''
    }
  },
  watch: {
    data() {
      this.tags = this.data
    }
  },
  methods: {
    handleTagClose(tag) {
      this.tags.splice(this.tags.indexOf(tag), 1)
      this.$emit('change', this.tags)
    },
    showKeywordsInput() {
      this.keywordsVisible = true
      this.$nextTick((_) => {
        this.$refs.saveKeywordsInput.$refs.input.focus()
      })
    },
    handleKeywordsInputConfirm() {
      if (this.limit > 0 && this.tags.length === this.limit) {
        this.$message.error(this.$t('jspTags.add_more_tips', { limit: this.limit }))
      } else if (this.tags.includes(this.keywordsInputValue)) {
        this.$message.error(this.$t('jspTags.exist_tips'))
      } else {
        if (this.keywordsInputValue) {
          this.tags.push(this.keywordsInputValue)
          this.$emit('change', this.tags)
        }
      }
      this.keywordsVisible = false
      this.keywordsInputValue = ''
    }
  }
}
</script>

<style>
</style>
